﻿#include "amplstepwindow.h"
#include "ui_amplstepwindow.h"
#include <mainwindow.h>
#include <eqptinfo.h>
extern intListener doorStatus;

class ReadOnlyDelegate: public QItemDelegate
{

public:
    ReadOnlyDelegate(QWidget *parent = NULL):QItemDelegate(parent)
    {}

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override //final
    {
        Q_UNUSED(parent)
        Q_UNUSED(option)
        Q_UNUSED(index)
        return NULL;
    }
};

amplStepWindow::amplStepWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::amplStepWindow)
{
    ui->setupUi(this);
    mpShadeWindow = new QWidget(this);

    label<<"Id"<<"ProgramId"<<"StepNum"<<"Temperature"<<"Rate"<<"ExecutionTime"<<"IsCollect"<<"CycleNumber"<<"CycleNum";
    QStringList  labels;
    labels<<QStringLiteral("ID") <<QStringLiteral("ProgramId")<< QStringLiteral("步骤编号") << QStringLiteral("温度(°C)") <<QStringLiteral("速率(°/s)") << QStringLiteral("时间(s)")<<QStringLiteral("是否采集")<<QStringLiteral("循环编号")<<QStringLiteral("循环数")<<QStringLiteral("操作");
    ui->tableWidget->setColumnCount(10);
    ui->tableWidget->setHorizontalHeaderLabels(labels);
    ui->tableWidget->resizeColumnsToContents(); //根据内容调整列宽
    ui->tableWidget->setColumnHidden(0, true); // 隐藏第1列
    ui->tableWidget->setColumnHidden(1, true); // 隐藏第1列
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->verticalHeader()->setHidden(true);
    ui->tableWidget->setInputMethodHints(Qt::ImhHiddenText);
    ui->tableWidget->setStyleSheet("background-color: rgb(235,243,255);");
    for(int i=0;i<ui->tableWidget->rowCount();i++){
        ui->tableWidget->setRowHeight(i, 50);
    }

    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget->columnCount(); ++column) {
        }
    }

    QRegExp regExp("^[\u4E00-\u9FA5a-zA-Z0-9_\\+\\-\\\\ \\/ \\( \\) \\.]+$");
    QRegExpValidator *validator = new QRegExpValidator(regExp, this);
    ui->programeName->setValidator(validator);
    ui->programeName->setMaxLength(30);

    ui->lineEdit->setValidator(validator);
    ui->lineEdit->setMaxLength(30);

    QIntValidator *numberValidator = new QIntValidator(this);
    numberValidator->setRange(0, 65535); // 设置接受的数字范围
    ui->lineEdit_2->setValidator(numberValidator);
    canRefInfo=true;
    QScroller::grabGesture(ui->tableWidget,QScroller::LeftMouseButtonGesture);
}

amplStepWindow::~amplStepWindow()
{
    delete ui;
}

void amplStepWindow::showEvent(QShowEvent *event){

    if(canRefInfo){
        logClient=loghelper::getInstance();
        tcpClient=TcpClient::getInstance();

        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        if(amplGuid.isNull() ||amplGuid.isEmpty()){
            QString sql="SELECT MAX(ID)+1 as StrGuid FROM AmplProgram";
            query.exec(sql);
            while(query.next()){
                if(query.value("StrGuid").toString().isNull() || query.value("StrGuid").toString().isEmpty()){
                    amplGuid="1";
                }else {
                    amplGuid=query.value("StrGuid").toString();
                }
            }
        }
        ui->lineEdit_2->setText(amplGuid);
        ui->programeName->setText("");
        ui->lineEdit->setText("");

        if(MainWindow::experimentStatus.get()==4){
            QString sql=QString("Select programName,Memo from AmplProgramTemp where id='%1'").arg(amplGuid);
            query.exec(sql);
            while (query.next()) {
                ui->programeName->setText(query.value("ProgramName").toString());
                ui->lineEdit->setText(query.value("Memo").toString());
            }
        }else{
            QString sql=QString("Select programName,Memo from AmplProgram where id='%1'").arg(amplGuid);
            query.exec(sql);
            while (query.next()) {
                ui->programeName->setText(query.value("ProgramName").toString());
                ui->lineEdit->setText(query.value("Memo").toString());
            }
        }


        if(doorStatus.get()==0)
        {
            ui->pushButton_5->setText("        打开仓门");
        }
        else
        {
            ui->pushButton_5->setText("        关闭仓门");
        }

        //查看可编辑 查看不可编辑 新建可编辑
        if(MainWindow::experimentStatus.get()==1 ||MainWindow::experimentStatus.get()==4){
            ui->lineEdit_2->setReadOnly(true);
            ui->programeName->setReadOnly(true);
            ui->lineEdit->setReadOnly(true);
            ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
            ui->pushButton_4->setEnabled(false);
            ui->pushButton_5->setEnabled(false);
            ui->label_8->setText("查看程序");
        }
        else
        {
            ui->lineEdit_2->setReadOnly(false);
            ui->programeName->setReadOnly(false);
            ui->lineEdit->setReadOnly(false);
            ui->tableWidget->setEditTriggers(QAbstractItemView::CurrentChanged);
            ui->pushButton_4->setEnabled(true);
            ui->pushButton_5->setEnabled(true);
            if(isReadStatus==0){
                ui->label_8->setText("新建程序");
            }else{
                ui->label_8->setText("查看程序");
            }
        }

        RefreshTableData();
        refShadeWindow();
        for(int i=0;i<ui->tableWidget->rowCount();i++){
            ui->tableWidget->setRowHeight(i, 50);
        }

        canRefInfo=false;
    }
}

void amplStepWindow::resizeEvent(QResizeEvent *event){
    refShadeWindow();
}

void amplStepWindow::refShadeWindow(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    if(mpShadeWindow){
        mpShadeWindow->close();
    }
    QString sql="Select * From IsFirstStartUp";
    query.exec(sql);

    bool isFirst=false;
    int guideStatus;
    while (query.next()) {
        isFirst = query.value("IsFirst").toString()=="0";
        guideStatus = query.value("GuideStatus").toInt();
    }

    if(isFirst){
        if(guideStatus==1)//扩增程序
        {
            mpShadeWindow = new QWidget(this);
            QString str("QWidget{background-color:rgba(0,0,0,0.6);}");   //0.6代表透明度，根据需要自行调整
            mpShadeWindow->setStyleSheet(str);
            QRect rect = this->geometry();
            int screenWidth = rect.width();  // 屏幕宽度
            int screenHeight = rect.height();  // 屏幕高度
            mpShadeWindow->setGeometry(0, 0,screenWidth,screenHeight);    //遮罩窗口位置

            QRect btnRect= ui->pushButton_4->frameGeometry();

            QLabel *label=new QLabel("2/4程序",mpShadeWindow);
            QPalette palette;
            palette.setColor(QPalette::WindowText, QColor(255,255,255));
            QFont font=label->font();
            font.setPointSize(24);
            label->setFont(font);
            label->setPalette(palette);
            label->setGeometry(btnRect.x()-40,screenHeight-160,180,30);
            label->setStyleSheet("background-color:rgba(0,0,0,0);");

            QPushButton * btnSkipThis = new QPushButton("跳过当前引导",mpShadeWindow);
            btnSkipThis->setGeometry(btnRect.x()-110,screenHeight-120,120,40);
            btnSkipThis->setStyleSheet("border-radius: 8px; background-color:#FFFFFF");

            QObject::connect(btnSkipThis, &QPushButton::clicked,[this](){
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);

                QString sql="Update IsFirstStartUp set GuideStatus=2";
                query.exec(sql);

                refShadeWindow();
            });

            QPushButton * btnSkipAll = new QPushButton("跳过全部引导",mpShadeWindow);
            btnSkipAll->setGeometry(btnRect.x()+20,screenHeight-120,120,40);
            btnSkipAll->setStyleSheet("border-radius: 8px; background-color:#2F42CD");

            QObject::connect(btnSkipAll, &QPushButton::clicked,[this](){
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);

                QString sql="Update IsFirstStartUp set IsFirst='1',GuideStatus=5";
                query.exec(sql);

                refShadeWindow();
            });

            QPushButton *btnSet=new QPushButton("保存",mpShadeWindow);
            btnSet->setGeometry(btnRect.x(),screenHeight-60,120,40);
            QFont btnFont=btnSet->font();
            font.setPointSize(12);
            btnSet->setFont(font);
            btnSet->setStyleSheet("background-color: qlineargradient(x1: 0, y0: 0, x2: 0, y2: 1, stop: 0 #8C97ED, stop: 1 #0018D1);border-radius: 8px; color: white;");

            QLabel *movieLabel=new QLabel("",mpShadeWindow);
            movieLabel->setGeometry(btnRect.x(),screenHeight-40,60,60);
            movieLabel->setStyleSheet("background-color:rgba(0,0,0,0);");

            QMovie  *guideMovie = new QMovie(":/pic/picture/guide.gif");
            movieLabel->setMovie(guideMovie);
            guideMovie->start();

            QObject::connect(btnSet, &QPushButton::clicked,[this](){
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);

                QString sql="Update IsFirstStartUp set GuideStatus=2";
                query.exec(sql);

                refShadeWindow();
            });

            mpShadeWindow->show();
        }
    }
}

void amplStepWindow::on_pushButton_2_clicked()
{
    this->close();

    canRefInfo=true;

    if(MainWindow::experimentStatus.get()==1)
    {
        emit changeExpProWindow();

    }
    else if(MainWindow::experimentStatus.get() == 4){
        emit changeExperimentInfoWindow();
    }
    else if(MainWindow::experimentStatus.get()==0){
        if(isReadStatus==0 || isReadStatus==1){
            emit changeAmplProWindow();
        }
        else
        {
            emit changeExperimentInfoWindow();
        }
    }
    else if(MainWindow::experimentStatus.get() == 5){
        emit changeExperimentInfoWindow();
    }
}

void amplStepWindow::RefreshTableData(){
    ui->tableWidget->blockSignals(true);

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql;
    if(MainWindow::experimentStatus.get()==4){
        sql=QString("Select count(*) as Num from AmplStepTemp where ProgramId='%1' order by StepNum").arg(amplGuid);

    }else{
        sql=QString("Select count(*) as Num from AmplStep where ProgramId='%1' order by StepNum").arg(amplGuid);
    }

    query.exec(sql);
    double dataNum=0;
    while (query.next()) {
        dataNum=query.value("Num").toDouble();
    }

    if(dataNum>0){
        if(MainWindow::experimentStatus.get()==4){
            sql=QString("Select * from AmplStepTemp where ProgramId='%1' order by StepNum").arg(amplGuid);

        }else{
            sql=QString("Select * from AmplStep where ProgramId='%1' order by StepNum").arg(amplGuid);
        }
        query.exec(sql);
        ui->tableWidget->setRowCount(0);
        int rowNum=0;

        while (query.next()) {
            ui->tableWidget->insertRow(rowNum);
            ui->tableWidget->setRowHeight(rowNum, 50);
            for (int l=0;l<label.length();l++) {
                ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(this);
                ui->tableWidget->setItemDelegateForColumn(2, readOnlyDelegate);
                if(l==6){
                    QComboBox *comboBox = new QComboBox();
                    comboBox->addItem("是");
                    comboBox->addItem("否");
                    comboBox->setCurrentText(query.value(label[l]).toString());
                    if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
                    {
                        comboBox->setEnabled(false);
                    }
                    ui->tableWidget->setCellWidget(rowNum, 6, comboBox);
                }else{
                    QTableWidgetItem *item = new QTableWidgetItem(query.value(label[l]).toString());
                    ui->tableWidget->setItem(rowNum, l, item);
                    ui->tableWidget->item(rowNum,l)->setTextAlignment(Qt::AlignCenter);
                }
            }
            QPushButton *delBtn = new QPushButton();
            delBtn->setText("删除");
            delBtn->setMinimumSize(50,40);

            QPushButton *addBtn=new QPushButton();
            addBtn->setText("添加");
            addBtn->setMinimumSize(50,40);

            if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4){
                delBtn->setEnabled(false);
                addBtn->setEnabled(false);
            }
            QWidget *tmp_widget = new QWidget();
            QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
            tmp_layout->addWidget(delBtn);
            tmp_layout->addWidget(addBtn);
            tmp_layout->setMargin(0);
            ui->tableWidget->setCellWidget(rowNum,9,tmp_widget);

            connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
            connect(addBtn, SIGNAL(clicked()), this,SLOT(addBtnClicked()));
            rowNum++;
        }
    }else {
        QString guid=common->GetGuid();


        ui->tableWidget->setRowCount(0);
        ui->tableWidget->insertRow(0);

        for (int l=0;l<label.length();l++) {
            ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(this);
            ui->tableWidget->setItemDelegateForColumn(2, readOnlyDelegate);

            if(l==0){
                QTableWidgetItem *item=new QTableWidgetItem(guid);
                ui->tableWidget->setItem(0, 0, item);
                ui->tableWidget->item(0,0)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==1){
                QTableWidgetItem *item=new QTableWidgetItem(amplGuid);
                ui->tableWidget->setItem(0, 1, item);
                ui->tableWidget->item(0,1)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==2){
                QTableWidgetItem *item = new QTableWidgetItem("1");

                ui->tableWidget->setItem(0, 2, item);
                ui->tableWidget->item(0,2)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==6){
                QComboBox *comboBox = new QComboBox();
                comboBox->addItem("是");
                comboBox->addItem("否");
                comboBox->setCurrentText("否");
                if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
                {
                    comboBox->setEnabled(false);
                }
                ui->tableWidget->setCellWidget(0, 6, comboBox);
            }
            else if(l==8){
                QTableWidgetItem *item = new QTableWidgetItem("1");

                ui->tableWidget->setItem(0, 8, item);
                ui->tableWidget->item(0,8)->setTextAlignment(Qt::AlignCenter);
            }
            else {
                QTableWidgetItem *item = new QTableWidgetItem("0");
                ui->tableWidget->setItem(0, l, item);
                ui->tableWidget->item(0,l)->setTextAlignment(Qt::AlignCenter);
            }
        }

        QPushButton *delBtn = new QPushButton();
        delBtn->setText("删除");
        delBtn->setMinimumSize(50,40);

        QPushButton *addBtn=new QPushButton();
        addBtn->setText("添加");
        addBtn->setMinimumSize(50,40);;
        if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
        {
            delBtn->setEnabled(false);
            addBtn->setEnabled(false);
        }
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
        tmp_layout->addWidget(delBtn);
        tmp_layout->addWidget(addBtn);
        tmp_layout->setMargin(0);
        ui->tableWidget->setCellWidget(0,9,tmp_widget);

        connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
        connect(addBtn, SIGNAL(clicked()), this,SLOT(addBtnClicked()));
    }
    ui->tableWidget->blockSignals(false);
}

void amplStepWindow::addBtnClicked(){
    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    QString stepNum = ui->tableWidget->item(index.row(),2)->text();//取出当前行第1列内容

    ui->tableWidget->insertRow(stepNum.toInt());
    ui->tableWidget->setRowHeight(stepNum.toInt(), 50);

    QString guid=common->GetGuid();

    for (int l=0;l<label.length();l++) {
        ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(this);
        ui->tableWidget->setItemDelegateForColumn(2, readOnlyDelegate);

        if(l==0){
            QTableWidgetItem *item=new QTableWidgetItem(guid);
            ui->tableWidget->setItem(stepNum.toInt(), 0, item);
            ui->tableWidget->item(stepNum.toInt(),0)->setTextAlignment(Qt::AlignCenter);
        }
        else if(l==1){
            QTableWidgetItem *item=new QTableWidgetItem(amplGuid);
            ui->tableWidget->setItem(stepNum.toInt(), 1, item);
            ui->tableWidget->item(stepNum.toInt(),1)->setTextAlignment(Qt::AlignCenter);
        }
        else if(l==6){
            QComboBox *comboBox = new QComboBox();
            comboBox->addItem("是");
            comboBox->addItem("否");
            comboBox->setCurrentText("否");
            if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
            {
                comboBox->setEnabled(false);
            }
            ui->tableWidget->setCellWidget(stepNum.toInt(), 6, comboBox);
        }
        else if(l==8){
            QTableWidgetItem *item = new QTableWidgetItem("1");
            ui->tableWidget->setItem(stepNum.toInt(), l, item);
            ui->tableWidget->item(stepNum.toInt(),l)->setTextAlignment(Qt::AlignCenter);
        }
        else {
            QTableWidgetItem *item = new QTableWidgetItem("0");
            ui->tableWidget->setItem(stepNum.toInt(), l, item);
            ui->tableWidget->item(stepNum.toInt(),l)->setTextAlignment(Qt::AlignCenter);
        }
    }

    QPushButton *delBtn = new QPushButton();
    delBtn->setText("删除");
    delBtn->setMinimumSize(50,40);

    QPushButton *addBtn=new QPushButton();
    addBtn->setText("添加");
    addBtn->setMinimumSize(50,40);;

    QWidget *tmp_widget = new QWidget();
    QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
    tmp_layout->addWidget(delBtn);
    tmp_layout->addWidget(addBtn);
    tmp_layout->setMargin(0);
    ui->tableWidget->setCellWidget(stepNum.toInt(),9,tmp_widget);

    connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
    connect(addBtn, SIGNAL(clicked()), this,SLOT(addBtnClicked()));

    for (int i=0;i<ui->tableWidget->rowCount();i++) {
        QTableWidgetItem *item=new QTableWidgetItem(QString::number(i+1));
        ui->tableWidget->setItem(i, 2, item);
        ui->tableWidget->item(i,2)->setTextAlignment(Qt::AlignCenter);
    }
}

void amplStepWindow::delBtnClicked(){

    QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "是否删除这个步骤", QMessageBox::Yes|QMessageBox::No, this);
    box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
    box->button(QMessageBox::No)->setText("取消");// 将原本显示“Yes”的按钮改为显示“确认”

    int res= box->exec();
    if(QMessageBox::Yes == res)
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QPushButton *btn = (QPushButton*)sender();
        QWidget *w_parent = (QWidget*)btn->parent();
        int x = w_parent->frameGeometry().x();
        int y = w_parent->frameGeometry().y();
        QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

        if(ui->tableWidget->rowCount()==1)
        {
            QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "至少需要保留一个步骤", QMessageBox::Yes, this);
            box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
            box->exec();
        }
        else
        {
            ui->tableWidget->removeRow(index.row());

            for (int i=0;i<ui->tableWidget->rowCount();i++) {
                QTableWidgetItem *item=new QTableWidgetItem(QString::number(i+1));
                ui->tableWidget->setItem(i, 2, item);
                ui->tableWidget->item(i,2)->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
}

void amplStepWindow::on_pushButton_4_clicked()
{
    QSqlDatabase db=dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql;

    db.transaction();

    //扩增程序编号校验
    if(ui->lineEdit_2->text().isNull() || ui->lineEdit_2->text().isEmpty()){
        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "扩增程序编号不能为空", QMessageBox::Yes, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->exec();
        db.rollback();
        return;
    }
    else
    {
        if(amplGuid!=ui->lineEdit_2->text()){
            sql=QString("SELECT count(*) as Result From AmplProgram Where id='%1';").arg(ui->lineEdit_2->text());
            query.exec(sql);
            bool rule = false;
            while (query.next()) {
                rule=query.value("Result").toInt()>0;
            }
            if(rule){
                QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "编号重复,请重新更改编号", QMessageBox::Yes, this);
                box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
                box->exec();
                return;
            }

            QString sql=QString("Delete From amplProgram where id='%1'").arg(amplGuid);
            query.exec(sql);
            sql=QString("Delete From AmplStep where ProgramId='%1'").arg(amplGuid);
            query.exec(sql);

            amplGuid=ui->lineEdit_2->text();

        }
    }

    for (int i=0;i<ui->tableWidget->rowCount();i++) {
        QString StepNum=ui->tableWidget->item(i,2)->text();
        QString temp=ui->tableWidget->item(i,3)->text();
        QString executionTime=ui->tableWidget->item(i,4)->text();
        QString CycleNumber=ui->tableWidget->item(i,7)->text();
        QString CycleNum=ui->tableWidget->item(i,8)->text();
        QString id=ui->tableWidget->item(i,0)->text();
        QString rate=ui->tableWidget->item(i,5)->text();

        QWidget *widgetSex=ui->tableWidget->cellWidget(i,6);
        QComboBox *sex=(QComboBox*)widgetSex;
        QString isCollect= sex->currentText();

        QString sql=QString("Insert or Replace into AmplStep Values('%1','%2','%3','%4',"
                            "'%5','%6','%7','%8','%9')").arg
                (id,amplGuid,StepNum,temp,rate,executionTime,isCollect,CycleNumber,CycleNum);
        query.exec(sql);

    }

    //扩增程序名称校验
    if(ui->programeName->text().isNull() || ui->programeName->text().isEmpty()){
        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "扩增程序名称不能为空", QMessageBox::Yes, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->exec();
        db.rollback();
        return;
    }
    else
    {
        sql=QString("SELECT count(*) as Result From AmplProgram Where id<>'%1' and ProgramName='%2';").arg(amplGuid,ui->programeName->text());
        query.exec(sql);
        bool rule = false;
        while (query.next()) {
            rule=query.value("Result").toInt()>0;
        }
        if(rule){
            QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "程序名称重复,请重新更改程序名称", QMessageBox::Yes, this);
            box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
            box->exec();
            return;
        }
    }

    sql=QString("Select count(*) as num From AmplStep Where ProgramId='%1' and IsCollect='是'").arg(amplGuid);
    query.exec(sql);
    bool collectNumWrong=false;
    while (query.next()) {
        collectNumWrong=query.value("num").toInt()>1;
    }
    if(collectNumWrong){
        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "最多有一个采集数据的步骤", QMessageBox::Yes, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->exec();
        db.rollback();
        return;
    }

    //填写内容校验
    sql=QString("SELECT CASE WHEN COUNTNum > 1 AND "
                "countRule > 0 THEN 1 ELSE 0 END as result "
                "FROM (SELECT count( * ) countNum "
                "FROM AmplStep "
                "WHERE programId = '%1' AND "
                "Temperature <> '' AND "
                "ExecutionTime <> ''),("
                "SELECT count( * ) countRule "
                "FROM AmplStep "
                "WHERE programId = '%1' AND "
                "Temperature <> '' AND ExecutionTime <> '' AND "
                "CycleNumber > 0 AND CycleNum > 1);").arg(amplGuid);
    query.exec(sql);
    bool rule = false;
    while (query.next()) {
        rule=query.value("Result").toInt()==1;
    }

    if(!rule){
        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "至少要包含两个步骤,并且需正确填写温度数据,循环数,循环编号", QMessageBox::Yes, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->exec();
        db.rollback();
        return;
    }
    else
    {
        double StepNum=0;
        double CycleNumber=0;
        double CycleNum=0;
        QString sql=QString("Select StepNum,CycleNumber,CycleNum "
                            "From AmplStep "
                            "where programId='%1' and "
                            "StepNum=(Select max(StepNum) from AmplStep where ProgramId='%1')").arg(amplGuid);

        query.exec(sql);
        while (query.next()) {
            StepNum=query.value("StepNum").toDouble();
            CycleNumber=query.value("CycleNumber").toDouble();
            CycleNum=query.value("CycleNum").toDouble();
        }

        eqptinfo eqInfo;
        QString addNum=eqInfo.calculateDurationread();

        double duration=0;
        sql=QString("Select sum(ExecutionTime + %4)*%1 as Result from AmplStep where ProgramId='%2' and StepNum>='%3'").arg(QString::number(CycleNum),amplGuid,QString::number(CycleNumber),addNum);
        query.exec(sql);
        while (query.next()) {
            duration+=query.value("Result").toDouble();
        }

        if(StepNum>1){
            sql=QString("Select sum((ExecutionTime + %3)*CycleNum) as Result from AmplStep where ProgramId='%1' and StepNum<'%2'").arg(amplGuid,QString::number(CycleNumber),addNum);
            query.exec(sql);
            while (query.next()) {
                duration+=query.value("Result").toDouble();
            }
        }
        QString durationResult;
        if(duration/3600>1){
            double hour=0;
            double min=0;
            double sec=0;

            std::div_t hourResult = std::div(duration, 3600);
            hour=hourResult.quot;

            std::div_t minResult = std::div(duration-hour*3600,60);
            min=minResult.quot;

            sec=duration-hour*3600-min*60;
            durationResult=QString::number(hour)+"时"+QString::number(min)+"分"+QString::number(sec)+"秒";
        }
        else if(duration/60>1){
            double min=0;
            double sec=0;
            std::div_t minResult = std::div(duration,60);
            min=minResult.quot;

            sec=duration-min*60;
            durationResult=QString::number(min)+"分"+QString::number(sec)+"秒";
        }
        else{
            durationResult=QString::number(duration)+"秒";
        }
        QString dateStr=common->GetDateTimeStr();
        sql=QString("Insert into AmplProgram values('%1','False','','','','%2','');").arg(amplGuid,dateStr);
        query.exec(sql);
        sql=QString("update amplProgram set "
                    "programName='%1',"
                    "Duration='%3',"
                    "StepNum=(Select count(*) from AmplStep where ProgramId='%2'),"
                    "Memo='%4' "
                    "where ID='%2'").arg(ui->programeName->text(),amplGuid,durationResult,ui->lineEdit->text());
        query.exec(sql);

        QMessageBox *box = new QMessageBox(QMessageBox::Question, "提示", "扩增程序信息保存成功", QMessageBox::Yes, this);
        box->button(QMessageBox::Yes)->setText("确认");// 将原本显示“Yes”的按钮改为显示“确认”
        box->exec();
    }
    db.commit();
}

void amplStepWindow::on_pushButton_5_clicked()
{
    if(doorStatus.get()==0)
    {
        doorStatus.set(1);
        ui->pushButton_5->setText("        关闭仓门");
    }
    else
    {
        doorStatus.set(0);
        ui->pushButton_5->setText("        打开仓门");
    }
}

void amplStepWindow::on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
    if(previousRow>=0 && previousColumn>=0){
        if(previousColumn!=6 && previousColumn!=9){
            QString info=ui->tableWidget->item(previousRow,previousColumn)->text();

            if(previousColumn==3){
                if(!info.isNull()&&!info.isEmpty()){
                    bool isNum;
                    double tempNum=info.toDouble(&isNum);
                    if(isNum)
                    {
                        if(tempNum>120||tempNum<4){
                            QTableWidgetItem *item=new QTableWidgetItem("");
                            ui->tableWidget->setItem(previousRow, 3, item);
                            ui->tableWidget->item(previousRow,3)->setTextAlignment(Qt::AlignCenter);
                            return;
                        }

                        if(QString::number(tempNum).contains(".")){
                            QList<QString> tempList=QString::number(tempNum).split(".");
                            if(tempList[1].length()>2){

                                QTableWidgetItem *item=new QTableWidgetItem("");
                                ui->tableWidget->setItem(previousRow, 3, item);
                                ui->tableWidget->item(previousRow,3)->setTextAlignment(Qt::AlignCenter);

                                return;
                            }
                        }
                    }
                    else
                    {
                        QTableWidgetItem *item=new QTableWidgetItem("");
                        ui->tableWidget->setItem(previousRow, 3, item);
                        ui->tableWidget->item(previousRow,3)->setTextAlignment(Qt::AlignCenter);
                        return;
                    }
                }

            }

            if(previousColumn==4){
                if(!info.isNull()&&!info.isEmpty()){
                    bool isNum;
                    int time=info.toInt(&isNum);
                    if(!isNum ){
                        QTableWidgetItem *item=new QTableWidgetItem("");
                        ui->tableWidget->setItem(previousRow, 4, item);
                        ui->tableWidget->item(previousRow,4)->setTextAlignment(Qt::AlignCenter);
                        return;
                    }else{
                        if(time<0 ||time>20){
                            QTableWidgetItem *item=new QTableWidgetItem("");
                            ui->tableWidget->setItem(previousRow, 4, item);
                            ui->tableWidget->item(previousRow,4)->setTextAlignment(Qt::AlignCenter);
                            return;
                        }
                    }
                }
            }

            if(previousColumn==5){
                if(!info.isNull()&&!info.isEmpty()){
                    bool isNum;
                    int time=info.toInt(&isNum);
                    if(!isNum || time<0){
                        QTableWidgetItem *item=new QTableWidgetItem("");
                        ui->tableWidget->setItem(previousRow, 5, item);
                        ui->tableWidget->item(previousRow,5)->setTextAlignment(Qt::AlignCenter);
                        return;
                    }
                }
            }

            if(previousColumn==7){
                if(!info.isNull()&&!info.isEmpty()){
                    bool isNum;
                    int cycleNumber=info.toInt(&isNum);
                    if(!isNum || cycleNumber<0)
                    {
                        QTableWidgetItem *item=new QTableWidgetItem("");
                        ui->tableWidget->setItem(previousRow, 7, item);
                        ui->tableWidget->item(previousRow,7)->setTextAlignment(Qt::AlignCenter);
                        return;
                    }else{
                        QString StepNum=ui->tableWidget->item(previousRow,2)->text();

                        if(cycleNumber!=0 && cycleNumber>=StepNum.toInt()){
                            QTableWidgetItem *item=new QTableWidgetItem("");
                            ui->tableWidget->setItem(previousRow, 7, item);
                            ui->tableWidget->item(previousRow,7)->setTextAlignment(Qt::AlignCenter);
                            return;
                        }
                    }
                }

            }

            if(previousColumn==8){

                if(!info.isNull()&&!info.isEmpty()){
                    bool isNum;
                    int cycleNum=info.toInt(&isNum);
                    if(!isNum || cycleNum<0){
                        QTableWidgetItem *item=new QTableWidgetItem("");
                        ui->tableWidget->setItem(previousRow, 8, item);
                        ui->tableWidget->item(previousRow,8)->setTextAlignment(Qt::AlignCenter);
                        return;
                    }
                    else
                    {
                        if(cycleNum >= 65)
                        {
                            QTableWidgetItem *item=new QTableWidgetItem("");
                            ui->tableWidget->setItem(previousRow, 8, item);
                            ui->tableWidget->item(previousRow,8)->setTextAlignment(Qt::AlignCenter);
                            return;
                        }
                    }
                }
            }
        }

    }
}
